package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.*;
import yxy.cherry.data.string.GameString;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.active.module.actcontrol.activeControl;
import yxy.game.pm2.active.module.actfavoritewarlord.FavouritePackage;
import yxy.game.pm2.active.module.subordinateclass.Act_许愿瓶大奖纪录;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Item;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.AreaModule;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.message.BottleWishMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.hitplanegame.HitPlaneGameModule;
import yxy.game.pm2.module.mail.MailHandle;
import yxy.game.pm2.module.mail.MailTypeEnum;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;

import java.util.*;

public class ActiveModule_心愿瓶 extends PlayerModule {

    //bean ----------------------------------------------------

    public static final int acttype = 506;

    private int day;       //当前天数

    private DateTime update;    //刷新时间

    private int totalChargeMoney; //总充钱数量

    private ArrayList<Integer> hasRewardDays = new ArrayList<Integer>();//已经领取的天数

    private HashMap<Integer, Integer> bottle = new HashMap<Integer, Integer>();//许愿瓶对应的心愿值 key 瓶子id  value 心愿值

    private ArrayList<FavouritePackage> dgifts = new ArrayList<FavouritePackage>();//心仪武将商品信息

    private ArrayList<FavouritePackage> accumulateDgifts = new ArrayList<FavouritePackage>();//累充信息

    private ArrayList<Integer> hasRewardId = new ArrayList<>();//领取过的累充礼包

    public ArrayList<Integer> getHasRewardId() {
        return hasRewardId;
    }

    public void setHasRewardId(ArrayList<Integer> hasRewardId) {
        this.hasRewardId = hasRewardId;
    }

    public int getTotalChargeMoney() {
        return totalChargeMoney;
    }

    public void setTotalChargeMoney(int totalChargeMoney) {
        this.totalChargeMoney = totalChargeMoney;
    }

    public ArrayList<FavouritePackage> getAccumulateDgifts() {
        return accumulateDgifts;
    }

    public void setAccumulateDgifts(ArrayList<FavouritePackage> accumulateDgifts) {
        this.accumulateDgifts = accumulateDgifts;
    }

    public ArrayList<FavouritePackage> getDgifts() {
        return dgifts;
    }

    public void setDgifts(ArrayList<FavouritePackage> dgifts) {
        this.dgifts = dgifts;
    }

    public HashMap<Integer, Integer> getBottle() {
        return bottle;
    }

    public void setBottle(HashMap<Integer, Integer> bottle) {
        this.bottle = bottle;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public DateTime getUpdate() {
        return update;
    }

    public void setUpdate(DateTime update) {
        this.update = update;
    }

    public ArrayList<Integer> getHasRewardDays() {
        return hasRewardDays;
    }

    public void setHasRewardDays(ArrayList<Integer> hasRewardDays) {
        this.hasRewardDays = hasRewardDays;
    }
    //func ----------------------------------------------------

    //充值累计
    public void addChargeMoney(int price) {
        int totalChargeMoney = getTotalChargeMoney();
        setTotalChargeMoney(totalChargeMoney + price / 100);
        set();
    }


    /**
     * 创建ActiveModule_武将直升活动
     *
     * @param playerCode
     */
    public static ActiveModule_心愿瓶 create(String playerCode) {
        AreaBean ab = AreaModule.area(playerCode);
        activeControl sai = activeControl.get(ab.getAreaId(), acttype);
        if (sai != null) {
            ActiveModule_心愿瓶 am = new ActiveModule_心愿瓶();
            am.setPlayerCode(playerCode);
            am.setTimeline(sai.getTimeline());
            am.reset(ab.getAreaId());
            am.set();
            return am;
        }
        return null;
    }

    public void update() {
        PlayerBean pb = PlayerBean.get(getPlayerCode());
        ServerBean sb = ServerBean.get(pb.getServerId());
        activeControl sai = activeControl.get(String.valueOf(sb.getAreaId()), String.valueOf(acttype));
        if (sai == null) {
            return;
        }

        // 区活动关闭，但自己活动没关闭，更新活动时间
        if (!sai.running()) {
            //回收
            try {
                //todo 活动关闭，清除背包的没消耗完的活动道具
                actwishdata data = DataCenter.getData(1, actwishdata.class);
                int costid = data.getCostid();//消耗的道具id
                //如果背包存在就转成对应物品邮件发送
                Currency currency = Item.get(getPlayerCode(), CurrencyType.CT_物品, costid);
                Currency currency1 = Item.get(getPlayerCode(), CurrencyType.CT_物品, 80017);//在线匹配入场券回收
                if (currency.getNumber() > 0 || currency1.getNumber() > 0) {
                    List<Currency> list1 = new ArrayList<>();
                    list1.add(currency);
                    list1.add(currency1);
                    item item_ = DataCenter.getData(costid, item.class);
                    item item_1 = DataCenter.getData(80017, item.class);
                    new CurrencyHandle().cost(getPlayerCode(), CCReason.活动_节日_转盘令清空, list1);

                    //邮件补偿
                    List<Currency> list2 = new ArrayList<>();
                    Currency reward = Currency.create(item_.getReclaimtype(), item_.getReclaimid(), currency.getNumber() * item_.getReclaimnum());
                    Currency reward1 = Currency.create(item_1.getReclaimtype(), item_1.getReclaimid(), currency1.getNumber() * item_1.getReclaimnum());
                    if(reward!=null)list2.add(reward);
                    if(reward1!=null)list2.add(reward1);
                    String title = GameString.活动结束自动回收_title().getText();
                    long num = currency.getNumber() + currency1.getNumber()  ;
                    String content = GameString.活动结束自动回收_msg("心愿瓶", "" + num, "" + item_.getName(), "" + num * item_.getReclaimnum()).getText();
                    new MailHandle().sendMail(getPlayerCode(), MailTypeEnum.Mail, title, content, CCReason.心愿瓶活动许愿道具清空, list2);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (!sai.running() && running()) {
            setTimeline(sai.getTimeline());
            set();
            return;
        }

        // 区活动开启，但自己没开启，重置活动
        if (sai.running() && !running()) {
            setTimeline(sai.getTimeline());
            reset(sb.getAreaId());
            //飞机玩法重置
            HitPlaneGameModule am = HitPlaneGameModule.create(getPlayerCode());
            am.set();

            set();
        }

        //更新天数(转天更新)
        DateTime now = DateTime.now();
        int days = ActiveUtil.days(getUpdate(), now);
        if (days >= 1) {
            DateTime startTime = sai.getTimeline().getStartTime();
            int activityHasPassTime = ActiveUtil.days(startTime, now) + 1;
            setDay(activityHasPassTime);
            setUpdate(now);
            set();
        }
    }

    //重置
    private void reset(int areaId) {
        //获取表的数据，初始化心愿值
        Map<String, actwish> allData = DataCenter.getAllData(actwish.class);
        HashMap<Integer, Integer> bottle = new HashMap<>();
        for (actwish value : allData.values()) {
            bottle.put(value.getId(), 0);
        }
        setBottle(bottle);
        setDay(1);
        setUpdate(DateTime.now());
        setHasRewardDays(new ArrayList<Integer>());
        Act_许愿瓶大奖纪录.removeAllFromRedis(areaId);//记录删除

        //商品重置
        Map<String, actwishshop> shopMap = DataCenter.getAllData(actwishshop.class);        //商品表

        setDgifts(new ArrayList<FavouritePackage>());
        for (actwishshop data : shopMap.values()) {
            FavouritePackage dgift = new FavouritePackage();
            dgift.setId(data.getId());
            dgift.setGoodsid(data.getPurchasever());
            dgift.setNumlimit(data.getNumber());//限购次数
            dgift.setType(data.getLimittype());//类型
            dgift.setBuyNum(0); //已购买次数；
            getDgifts().add(dgift);
        }
        //总充值金额
        setTotalChargeMoney(0);
        //累充奖励
        setAccumulateDgifts(new ArrayList<FavouritePackage>());
        Map<String, actwishchargereward> accumulateMap = DataCenter.getAllData(actwishchargereward.class);
        for (actwishchargereward data : accumulateMap.values()) {
            FavouritePackage dgift = new FavouritePackage();
            dgift.setId(data.getId());
            getAccumulateDgifts().add(dgift);
        }

        setHasRewardId(new ArrayList<>());
    }

    public Collection<BottleWishMessage.BottleWishAwardsInfo> getLog(int areaId) {
        List<BottleWishMessage.BottleWishAwardsInfo> list = new ArrayList<>();
        try {
            List<Act_许愿瓶大奖纪录> msgs = Act_许愿瓶大奖纪录.all(areaId);
            for (Act_许愿瓶大奖纪录 msg : msgs) {
                BottleWishMessage.BottleWishAwardsInfo.Builder ai = BottleWishMessage.BottleWishAwardsInfo.newBuilder();
                ai.setSequence(msg.getTime());
                ai.setItem(new CurrencyHandle().packItem(msg.getCur()));
                ai.setName(msg.getName());
                list.add(ai.build());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return list;
    }


    /**
     * 解锁单 加 设置购买时间
     *
     * @param goodsid
     */
    public void unlockGiftPackageAndSetBuyTime(int goodsid) {
        for (FavouritePackage dgift : getDgifts()) {
            if (dgift.getGoodsid() == goodsid) {
                int buyNum = dgift.getBuyNum();
                buyNum++;
                dgift.setBuyNum(buyNum); //修改已购买数量
                set();
            }
        }
    }


    // redis ---------------------------------------------------------

    static private String key(String playerCode) {
        return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
    }

    public void set() {
        try {
            setv(key(getPlayerCode()), this);
            check();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 ActiveModule_心愿瓶
     *
     * @param playerCode
     * @return
     */
    public static ActiveModule_心愿瓶 get(String playerCode, Boolean isNewPlayer) {
        try {
            ActiveModule_心愿瓶 module = getv(key(playerCode));
            if (module == null) {

                //新用户不需要去查数据库
                if (!isNewPlayer) {
                    module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_心愿瓶.class);
                    if (module != null) {
                        module.set();
                    }//同步到redis
                }

                if (module == null) {
                    module = create(playerCode);
                }
            }

            module.update();
            module.check();
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看是否有可领取奖励 控制红点
     */
    public void check() {
        if (running()) {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
        } else {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
        }

        if (running()) {
            //签到能领取红点提示
            signInTipe();
            //某个瓶子心愿值>100红点提示
            bottleWishTipe();
        } else {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
        }

    }

    /**
     * 某个瓶子心愿值>100红点提示  能许愿也加红点
     */
    private void bottleWishTipe() {
        try {
            HashMap<Integer, Integer> bottle = getBottle();
            Map<String, actwish> allData = DataCenter.getAllData(actwish.class);
            for (actwish data : allData.values()) {
                Integer totalWish = bottle.get(data.getId());
                int score = data.getConversionScore();
                if (totalWish >= score) {
                    new TipHandle().updateTip(getPlayerCode(), TipType.活动_心愿瓶许愿领取红点, true);
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        new TipHandle().updateTip(getPlayerCode(), TipType.活动_心愿瓶许愿领取红点, false);
    }

    /**
     * 签到能领取红点提示
     */
    private void signInTipe() {
        ArrayList<Integer> hasRewardDays = getHasRewardDays();

        if (hasRewardDays.size() < getDay() && hasRewardDays.size() < 7) {
            new TipHandle().updateTip(getPlayerCode(), TipType.活动_心愿瓶签到红点, true);
            return;
        }

        new TipHandle().updateTip(getPlayerCode(), TipType.活动_心愿瓶签到红点, false);
    }


    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                ActiveModule_心愿瓶 activeModule_心愿瓶 = getv(key(playerCode));
                MySQLCacheDAO.setV(key, activeModule_心愿瓶);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }
    // lock==========================================================================

    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }


}
